import React, {useRef, useState} from 'react';
import {Image, navigateTo, Text, View} from 'remax/wechat';
import globalStyle from '@/style/index.less';
import styles from './index.less';
import VanButton from '@vant/weapp/lib/button';
import VanIcon from '@vant/weapp/lib/icon';
import VanSwipeCell from '@vant/weapp/lib/swipe-cell';
import VanSearch from '@vant/weapp/lib/search';
import clsx from 'clsx';
// import {apiDeleteDriver, apiGetDriverList} from '@/api/order';
import List from '@/components/list';
// import {DriverListItem} from '@/interface/order/driver';
import usePageBack from '@/hooks/use-page-back';
import {DRIVER_AUDIT_STATUS} from '@/utils/constant';
import useCustomDialog from '@/hooks/use-custom-dialog';
import useCustomToast from '@/hooks/use-custom-toast';

interface DriverListItem {
    driverId: number;
    driverName: string; // "姓名"
    phone: string; //"电话"
    idNum: string; //身份证号
    driverYear: number; //驾龄
    carModels: string; //准驾驶车型
    drivingLicensePic1: string; //' "驾照正面照的url"
    drivingLicensePic2: string; // "驾照背面照的url"
    authPic: string; //"授权书照的url"
    auditStatus: number; //审核状态，0 待审核；1 审核不通过；2 审核通过;3 已冻结
    auditRemark: string; //"审核未通过时的理由";
    canDrive: number; //可驾驶状态，1 可驾驶，0 不可驾驶
    createTime: string; // "yyyy-MM-dd HH:mm:ss" 创建时间
    unClosedTrain: number; // 是否有未结束的培训预约  0：没有 1有
}

export default function Driver(): JSX.Element {
    const [tableData, setTableData] = useState<DriverListItem[]>([]);
    const [listFinish, setListFinish] = useState(false);
    const listRef = useRef<{ reload: () => void }>();
    const {dialog, showDialog} = useCustomDialog();
    const {toast, showToast} = useCustomToast();
    const [searchKeyword, setSearchKeyword] = useState('');

    /**
     * @description 获取驾驶员列表数据方法
     */
    async function getListData(count: number) {
        const param = {
            keyword: searchKeyword,
            pageNum: count,
            pageSize: 10
        };
        const resultData = {} as any; //= await apiGetDriverList(param);
        if (count * 10 >= resultData.data.total) {
            setListFinish(true);
        }
        setTableData([...tableData, ...resultData.data.list]);
    }

    /**
     * @description 点击每一个驾驶员模块跳转到驾驶员信息详情
     */
    const detail = (id: number) => () => {
        navigateTo({url: '../driver-detail/index?id='+id});
    };

    /**
     * @description 扣分记录按钮
     */
    const goToDeductRecord = (id: number) => () => {
        navigateTo({url: '../deduct-record/index?id='+id});
    };

    /**
     * @description 培训记录按钮
     */
    const goToTrainRecord = (id: number) => () => {
        navigateTo({url: '../train-record/index?id='+id});
    };

    /**
     * @description 培训预约按钮
     */
    const goToTrain = (id: number, hasTrain: number) => () => {
        if(hasTrain){
            showToast({
                message: '当前已有培训预约！不可重复预约！',
                type: 'fail',
                duration: 2000
            });
        } else {
            navigateTo({url: '../training/index?id='+id});
        }
    };

    /**
     * @description 修改信息
     */
    const edit = (id: number) => ()=> {
        navigateTo({url: '../add-driver/index?id='+id});
    };

    /**
     * @description 添加驾驶员
     */
    const addDriver = () => {
        navigateTo({
            url: '../add-driver/index'
        });
    };

    /**
     * @description 页面重新载入刷新列表方法
     */
    usePageBack(() => {
        console.log('page back');
        listRef.current && listRef.current.reload();
    });

    const onChange = (e: any) => {
        setSearchKeyword(e.detail);
    };

    const listItems = tableData.map((item) => {
        let stateItem: React.ReactNode = null;
        const drive = item.canDrive === 1 ? '可驾驶' : '不可驾驶';
        switch (item.auditStatus) {
            case DRIVER_AUDIT_STATUS.TO_AUDIT:
                stateItem = <View className={clsx(styles.status, styles.toAudit)}>待审核({drive})</View>;
                break;
            case DRIVER_AUDIT_STATUS.NO_PASS:
                stateItem = <View className={clsx(styles.status, styles.hasRejected)}>未通过({drive})</View>;
                break;
            case DRIVER_AUDIT_STATUS.PASS:
                stateItem = <View className={clsx(styles.status, styles.approved)}>已通过({drive})</View>;
                break;
            case DRIVER_AUDIT_STATUS.FREEZE:
                stateItem = <View className={clsx(styles.status, styles.frozen)}>已冻结({drive})</View>;
                break;
            default:
                break;
        }
        return (
            <VanSwipeCell key={item.driverId} right-width={65}>
                <View className={styles.itemWrap}>
                    <View className={styles.item}>
                        <View className={styles.head} onClick={detail(item.driverId)}>
                            <View>
                                <Image className={styles.icon} src="/image/time-icon.png"/>
                                <Text>{item.createTime}</Text>
                            </View>
                            <VanIcon name="arrow"/>
                        </View>
                        <View className={styles.body}>
                            <View className={styles.name}>
                                <Text>{item.driverName}</Text>
                                {stateItem}
                            </View>
                            <View className={styles.dataList}>
                                <View>
                                    <View className={styles.dataTitle}>联系电话</View>
                                    <View className={styles.dataContent}>{item.phone}</View>
                                </View>
                                <View>
                                    <View className={styles.dataTitle}>驾龄</View>
                                    <View className={styles.dataContent}>{item.driverYear}</View>
                                </View>
                                <View>
                                    <View className={styles.dataTitle}>准驾车型</View>
                                    <View className={clsx(styles.dataContent, styles.driveType)}>{item.carModels}</View>
                                </View>
                            </View>
                        </View>
                        <View className={styles.footer}>
                            {
                                item.auditStatus === DRIVER_AUDIT_STATUS.NO_PASS &&
                                <View className={clsx(styles.more, styles.errorMsg)}>
                                    <Text className={styles.title}>未通过理由：</Text>
                                    <Text className={styles.msg}>{item.auditRemark}</Text>
                                </View>
                            }
                            <View className={styles.moreBtn}>
                                {
                                    ( item.auditStatus === DRIVER_AUDIT_STATUS.PASS || item.auditStatus === DRIVER_AUDIT_STATUS.FREEZE ) &&
                                    <VanButton class={styles.gutter} plain round size="small" type="info" bind:click={goToDeductRecord(item.driverId)}>扣分记录</VanButton>
                                }
                                {
                                    ( item.auditStatus === DRIVER_AUDIT_STATUS.PASS || item.auditStatus === DRIVER_AUDIT_STATUS.FREEZE ) &&
                                    <VanButton plain round size="small" type="info" bind:click={goToTrainRecord(item.driverId)}>培训记录</VanButton>
                                }
                            </View>
                            {
                                ( item.auditStatus === DRIVER_AUDIT_STATUS.PASS ) && (item.driverYear >= 3) &&
                                <VanButton plain round size="small" type="info" bind:click={goToTrain(item.driverId, item.unClosedTrain)}>培训预约</VanButton>
                            }
                            {
                                ( item.auditStatus === DRIVER_AUDIT_STATUS.TO_AUDIT || item.auditStatus === DRIVER_AUDIT_STATUS.NO_PASS ) &&
                                <VanButton plain round size="small" type="info" bind:click={edit(item.driverId)}>修改信息</VanButton>
                            }
                        </View>
                    </View>
                </View>
                <View slot="right" className={styles.swipeAction}>
                    <View
                        className={styles.icon}
                        onClick={async () => {
                            try {
                                await showDialog({
                                    title: '是否删除当前驾驶人？',
                                    showCancelButton: true
                                });
                            } catch (e) {
                                return;
                            }
                            // await apiDeleteDriver(item.driverId);
                            listRef.current?.reload();
                        }}
                    >
                        <VanIcon name="delete-o" color="#ffffff" size={24}/>
                    </View>
                </View>
            </VanSwipeCell>
        );
    });

    return (
        <View className={clsx(styles.driver, globalStyle.withBottomActions, globalStyle.noMargin)}>
            <VanSearch
                class={styles.searchBar}
                use-left-icon-slot
                use-right-icon-slot
                right-icon="search"
                maxlength={18}
                value={searchKeyword}
                bind:change={onChange}
                shape="round"
                placeholder="搜索姓名、联系电话、身份证号"
            >
                <View slot="right-icon" className={styles.searchIcon} onClick={() => {
                    // 如果未输入数据，不能搜索数据
                    if (!searchKeyword) return;
                    listRef.current && listRef.current.reload();
                }}>
                    <VanIcon name="search" size="20px"/>
                </View>
            </VanSearch>
            <List ref={listRef} finished={listFinish} empty={listItems.length === 0} className={styles.content}
                  load={getListData} refresherEnabled
                  onPreRefresh={() => {
                      setTableData([]);
                  }}
                  onRefresh={() => {
                      setListFinish(false);
                  }}>
                <View className={styles.listItems}>
                    {listItems}
                </View>
            </List>
            <View className={globalStyle.bottomActions}>
                <VanButton type="info" block round bind:click={addDriver}>
                    <View className={styles.buttonText}>
                        <VanIcon name="plus"/>
                        <Text className={styles.gutter}>添加驾驶人员</Text>
                    </View>
                </VanButton>
            </View>
            {dialog}
            {toast}
        </View>
    );
}
